package com.smsc.headend.task.engine.utils;

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESWrapEngine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

/**
 * @author wxh
 * @date 2021/3/30 11:27
 */
public class AesUtils {
    public static byte[] wrap(byte[] key, byte[] data) {
        AESWrapEngine engine = new AESWrapEngine();
        KeyParameter params = new KeyParameter(key);
        engine.init(true, params);

        return engine.wrap(data, 0, data.length);
    }

    public static byte[] unwrap(byte[] key, byte[] data) {
        AESWrapEngine engine = new AESWrapEngine();
        CipherParameters params = new KeyParameter(key);
        engine.init(false, params);

        try {
            return engine.unwrap(data, 0, data.length);
        } catch (InvalidCipherTextException icte) {
            return null;
        }
    }

    public static String wrap(String key, String data) {
        byte[] keyBuf = Hex.decode(key);
        byte[] dataBuf = Hex.decode(data);
        return Hex.toHexString(wrap(keyBuf, dataBuf)).toUpperCase();
    }

    public static String unwrap(String key, String data) {
        byte[] keyBuf = Hex.decode(key);
        byte[] dataBuf = Hex.decode(data);
        return Hex.toHexString(unwrap(keyBuf, dataBuf)).toUpperCase();
    }

}
